package com.cumt.threeway.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cumt.threeway.R;
import com.cumt.threeway.constant.ThreeWayConstant;
import com.cumt.threeway.constant.URLS;
import com.cumt.threeway.util.ThreeWayData;
import com.cumt.threeway.util.ThreeWayUtil;
import com.cumt.threeway.view.dialog.NeedLoginDialog;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 胡晶晶 on 2016/5/24.
 */
public class WriteStrategyActivity extends FragmentActivity implements View.OnClickListener{

    private EditText mTitleEditText;
    private EditText mContentEditText;
    private RequestQueue queue;
    private String mDate;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_startegy);
        initView();
    }

    private void initView() {
        queue = Volley.newRequestQueue(this);
        mTitleEditText = (EditText) findViewById(R.id.et_title);
        mContentEditText = (EditText) findViewById(R.id.et_content);
        findViewById(R.id.btn_back).setOnClickListener(this);
        findViewById(R.id.tv_confirm).setOnClickListener(this);

        SimpleDateFormat sDateFormat= new SimpleDateFormat("yyyy-MM-dd");
        mDate = sDateFormat.format(new java.util.Date());
    }

    private String getEditContent(EditText editText) {
        return editText.getText().toString();
    }

    @Override
    public void onClick(View v) {
        if(v == null) {
            return;
        }
        switch (v.getId()) {
            case R.id.btn_back:
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.tv_confirm:
                String title = getEditContent(mTitleEditText);
                String content = getEditContent(mContentEditText);
                if(TextUtils.isEmpty(ThreeWayUtil.getInstance().getLoginAccount(WriteStrategyActivity.this))) {
                    NeedLoginDialog needLoginDialog = NeedLoginDialog.newInstance("writeStrategy");
                    needLoginDialog.show(getSupportFragmentManager(),"needLoginDialog");
                } else {
//                    submitDataToServer();
                    submit();
                }
                break;
        }
    }

    private void submit() {
        if(TextUtils.isEmpty(getEditContent(mTitleEditText)) || TextUtils.isEmpty(getEditContent(mContentEditText))) {
            ThreeWayUtil.getInstance().showToast(this,getResources().getString(R.string.title_error));
            return;
        }
        String userName = ThreeWayUtil.getInstance().getUserName(this);
        ThreeWayData.getInstance().addMyGonglue(getEditContent(mTitleEditText), getEditContent(mContentEditText), userName);
//        ThreeWayUtil.getInstance().showToast(WriteStrategyActivity.this, getResources().getString(R.string.fabiao_success));
        Toast.makeText(this, getResources().getString(R.string.fabiao_success), Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    private void submitDataToServer() {
        if(TextUtils.isEmpty(getEditContent(mTitleEditText)) || TextUtils.isEmpty(getEditContent(mContentEditText))) {
            ThreeWayUtil.getInstance().showToast(this,getResources().getString(R.string.title_error));
            return;
        }
        StringRequest srPost = new StringRequest(Request.Method.POST,
                URLS.IP + "NetServlet/AddToGonglue",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String dingdan = response.toString();
                        if (dingdan.equals("true\r\n")) {
                            ThreeWayUtil.getInstance().showToast(WriteStrategyActivity.this, getResources().getString(R.string.fabiao_success));
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    setResult(RESULT_OK);
                                    finish();
                                }
                            },600);
                        } else {
                            ThreeWayUtil.getInstance().showToast(WriteStrategyActivity.this, getResources().getString(R.string.net_error));
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            // 当手机发送请求时，回调用getParams方法，拼请求
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("title", getEditContent(mTitleEditText));
                map.put("content", getEditContent(mContentEditText));
                map.put("date", mDate);
                map.put("loginTel",ThreeWayUtil.getInstance().getLoginAccount(WriteStrategyActivity.this));
                map.put("username", ThreeWayUtil.getInstance().getUserName(WriteStrategyActivity.this));
                return map;
            }
        };
        queue.add(srPost);
    }

    public void goLoginActivityForResult() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivityForResult(intent, ThreeWayConstant.INTENT_KEY_TO_LOGIN_2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ThreeWayConstant.INTENT_KEY_TO_LOGIN_2) {
            if(resultCode == RESULT_OK) {
//                submitDataToServer();
                submit();
            }
        }
    }
}
